package main

import (
	"io"
)

type monitoredReader struct {
	r         io.Reader
	direction string
	conn      *monitoredConnection
	// buffer    []byte // 添加缓冲区
	// mu        sync.Mutex
}

func newMonitoredReader(r io.Reader, direction string, conn *monitoredConnection) *monitoredReader {
	mr := &monitoredReader{
		r:         r,
		direction: direction,
		conn:      conn,
		// buffer:    make([]byte, 0), // 初始化缓冲区
	}
	// 启动一个 Goroutine 来处理数据
	// go mr.processData()
	return mr
}

func (mr *monitoredReader) Read(p []byte) (n int, err error) {
	n, err = mr.r.Read(p)
	if n > 0 {
		remainingBytes := n
		for remainingBytes > 0 {
			buffer := bufferPool.Get().([]byte)
			copySize := min(bufferSize, remainingBytes)
			copy(buffer[:copySize], p[n-remainingBytes:])
			if mr.direction == "MySQL到代理" {
				mr.conn.recvChannel <- buffer[:copySize]
			} else if mr.direction == "客户端到代理" {
				mr.conn.sendChannel <- buffer[:copySize]
			}
			remainingBytes -= copySize
		}

		// data := make([]byte, n)
		// copy(data, p[:n])
		// if mr.direction == "MySQL到代理" {
		// 	mr.conn.recvChannel <- data
		// } else if mr.direction == "客户端到代理" {
		// 	mr.conn.sendChannel <- data
		// }
		// 将读取到的数据发送到数据通道

		// mr.packetChan <- append([]byte{}, p[:n]...)
		// mu.Lock()
		// defer mu.Unlock()
		// // mr.mu.Lock()
		// defer mr.mu.Unlock()
		// mr.buffer = append(mr.buffer, p[:n]...)
		// mr.parseBuffer()
	}
	return
}
